<?php

namespace app\controller\admin\calendar2;

use app\model\admin\calendar2\Calendar2Game;
use app\model\admin\Menu;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Game extends Backend
{
    protected $model;
    protected $noNeedAuth = ['index', 'info'];

    protected $relationPrefix = "calendar2";

    public function initialize()
    {
        $this->model = new Calendar2Game();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where   = $this->buildSearchParams();
        $order   = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data  = $this->model->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item){
                if(isset($item['url'])&&!empty($item['url'])){
                    $item['url'] = imgUrlToAbsolute($item['url']);
                }
                if(isset($item['game_preview_url'])&&!empty($item['game_preview_url'])){
                    $item['game_preview_url'] = "<a style='color: #4e6ef2' href='".$item['game_preview_url']."' target='_blank' >".$item['game_preview_url']."</a>";

                }
                if(isset($item['icon'])&&!empty($item['icon'])){
                    $item['icon'] = imgUrlToAbsolute($item['icon']);
                }
                if(isset($item['grab_status'])&&!empty($item['grab_status'])){
                    if($item['grab_status']==1){
                        $item['grab_status'] = "<p style='color: #5FB878'>成功</p>";
                    }else{
                        $item['grab_status'] =  "<p style='color: red'>失败</p>";
                    }
                }
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());
        try {
            Db::startTrans();
            $post['create_time'] = date("Y-m-d H:i:s");
            $post['update_time'] = date("Y-m-d H:i:s");
            $res = strpos($post['game_url'],"isPreview");
            if($res===false){
                $data = explode("?",$post['game_url']);
                if(count($data)>1){
                    $data[1] = "isPreview=1&".$data[1];
                    $post['game_preview_url'] = implode("?",$data);
                }else{
                    $post['game_preview_url'] = $post['game_url']."?isPreview=1";
                }
            }else{
                $post['game_preview_url'] = $post['game_url'];
            }
            if(isset($post['laytpUploadFile']))unset($post['laytpUploadFile']);
            $id = (new Calendar2Game())->insertGetId($post);
            if ($id) {
                if(!$this->saveMenu($this->relationPrefix.$id,$id, $post['name'])){
                    return $this->error('添加菜单失败');
                }
                Db::commit();
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                Db::rollback();
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $id   = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $post = CommonFun::filterPostData($this->request->post());
        $res = strpos($post['game_url'],"isPreview");
        if($res===false){
            $data = explode("?",$post['game_url']);
            if(count($data)>1){
                $data[1] = "isPreview=1&".$data[1];
                $post['game_preview_url'] = implode("?",$data);
            }else{
                $post['game_preview_url'] = $post['game_url']."?isPreview=1";
            }
        }else{
            $post['game_preview_url'] = $post['game_url'];
        }
        IF(isset($post->icon)&&!empty($post->icon)){
            $post->icon = getRelativeUrl( $post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }

        try {
            Db::startTrans();
            $updateRes = $info->save();
            if ($updateRes) {

                $menuModel = new Menu();
                $detail = $menuModel->where("name", "新日历工具")->find();
                if (!$detail) {
                    return $this->error('缺少日历工具菜单');
                }
                $menuModel->where('relation_id',$post['id'])->where('pid',$detail->id)->save(
                    ['name'=>$post['name']]
                );
                Db::commit();
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                Db::rollback();

                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    protected function saveMenu($relationId, $gameId, $name)
    {
        $menuModel = new Menu();
        $detail = $menuModel->where("name", "新日历工具")->find();
        if (!$detail) {
            return false;
        } else {
            $detail = $detail->toArray();
            $menuOne = [
                'name' => $name,
                'is_menu' => 1,
                'sort' => 99,
                'pid' => $detail['id'],
                'relation_id' => $relationId,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            $pid = $menuModel->insertGetId($menuOne);
            if(!$pid){
                return false;
            }
            //日历配置
            $menuConfig = [
                'name' => "日历配置",
                'is_menu' => 1,
                'href' => "/admin/calendar2/config/edit.html?game_id=".$gameId,
                'sort' => 99,
                'pid' => $pid,
                'relation_id' => $relationId,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            $configPid = $menuModel->insertGetId($menuConfig);
            if(!$configPid){
                return false;
            }
            $menuList = [
                ['name' => "编辑",'rule'=>'/admin.calendar2.config/edit?game_id='.$gameId,'pid' =>$configPid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")]
            ];
            $menuModel->insertAll($menuList);
            //模块管理
            $menuModule = [
                'name' => "模块管理",
                'is_menu' => 1,
                'href' => "/admin/calendar2/module/index.html?game_id=".$gameId,
                'sort' => 99,
                'pid' => $pid,
                'relation_id' => $relationId,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            $modulePid = $menuModel->insertGetId($menuModule);
            if(!$modulePid){
                return false;
            }
            $menuList = [
                ['name' => "新增",'rule'=>'/admin.calendar2.module/add?game_id='.$gameId,'pid' =>$modulePid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "编辑",'rule'=>'/admin.calendar2.module/edit?game_id='.$gameId,'pid' =>$modulePid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "显示",'rule'=>'/admin.calendar2.module/setStatus','pid' =>$modulePid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "排序",'rule'=>'/admin.calendar2.module/setSort','pid' =>$modulePid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "删除",'rule'=>'/admin.calendar2.module/del?game_id='.$gameId,'pid' =>$modulePid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
            ];
            $menuModel->insertAll($menuList);

            //内容管理
            $menuContent = [
                'name' => "内容管理",
                'is_menu' => 1,
                'href' => "/admin/calendar2/content/index.html?game_id=".$gameId,
                'sort' => 99,
                'pid' => $pid,
                'relation_id' => $relationId,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            $contentPid= $menuModel->insertGetId($menuContent);
            if(!$contentPid){
                return false;
            }
            $menuList = [
                ['name' => "新增",'rule'=>'/admin.calendar2.content/add?game_id='.$gameId,'pid' =>$contentPid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "编辑",'rule'=>'/admin.calendar2.content/edit?game_id='.$gameId,'pid' =>$contentPid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "展示状态",'rule'=>'/admin.calendar2.content/setStatus','pid' =>$contentPid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "订阅状态",'rule'=>'/admin.calendar2.content/setSubscribeStatus','pid' =>$contentPid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "删除",'rule'=>'/admin.calendar2.content/del?game_id='.$gameId,'pid' =>$contentPid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
            ];
            $menuModel->insertAll($menuList);

            //内容审核
            $menuGrabContent = [
                'name' => "内容审核",
                'is_menu' => 1,
                'href' => "/admin/calendar2/grab_content/index.html?game_id=".$gameId,
                'sort' => 99,
                'pid' => $pid,
                'relation_id' => $relationId,
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s")
            ];
            $grabContentPid= $menuModel->insertGetId($menuGrabContent);
            if(!$grabContentPid){
                return false;
            }
            $menuList = [
                ['name' => "抓取",'rule'=>'/admin.calendar2.grabContent/grab?game_id='.$gameId,'pid' =>$grabContentPid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "编辑",'rule'=>'/admin.calendar2.grabContent/edit?game_id='.$gameId,'pid' =>$grabContentPid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "删除",'rule'=>'/admin.calendar2.grabContent/del?game_id='.$gameId,'pid' =>$grabContentPid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
                ['name' => "提交",'rule'=>'/admin.calendar2.grabContent/submit?game_id='.$gameId,'pid' =>$grabContentPid , 'is_menu' => 2, 'sort' => 0, 'relation_id' => $relationId, 'create_time' => date("Y-m-d H:i:s"), 'update_time' => date("Y-m-d H:i:s")],
            ];
            $menuModel->insertAll($menuList);
            return  true;
        }
    }

    //删除
    public function del()
    {
        $ids = array_filter($this->request->post('ids'));
        if (!$ids) {
            return $this->error('参数ids不能为空');
        }
        try {
            Db::startTrans();
            if ($this->model->destroy($ids)) {
                (new Menu())->whereIn('relation_id', $ids)->delete();
                Db::commit();
                $this->clearCache();
                return $this->success('数据删除成功');
            } else {
                Db::rollback();
                return $this->error('数据删除失败');
            }

        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }
}